<template>
  <d2-container>
    <el-row :gutter="20">
      <el-col :span="5">
        <el-scrollbar class="w-full h-full">
          <area-tree @nodeChange="treeNodeChange"></area-tree>
        </el-scrollbar>
      </el-col>
      <el-col :span="19">
        <div>
          <span class="theme-front-color">分类能耗：</span>
          <el-select v-model="dataForm.energyType" size="small">
          <el-option
            v-for="(item, index) in meterTypeList" :key="index"
            :label="item.paramValue"
            :value="item.paramKey">
          </el-option>
          </el-select>
          <el-button type="primary" size="small" icon="el-icon-search" style="margin-left:16px;" @click="getPowerDataListAll">查询</el-button>
        </div>

        <div class="mt-6">
          <div>
            <el-button plain icon="el-icon-arrow-left" size="small" @click="addDate(-1)"></el-button>
            <el-date-picker v-model="dataForm.dayDate" value-format="yyyyMMdd" type="date" @change="getPowerDataList('1')" placeholder="请选择" size="small" style="margin:0 16px;"></el-date-picker>
            <el-button plain icon="el-icon-arrow-right" size="small" @click="addDate(1)"></el-button>
          </div>
          <div id="energyTrend_analysis_bar1" style="height:300px;" class="mt-2"></div>
        </div>
        
        <div class="mt-6">
          <div>
            <el-button plain icon="el-icon-arrow-left" size="small" @click="addMonth(-1)"></el-button>
            <el-date-picker v-model="dataForm.monthDate" type="month" value-format="yyyyMM" @change="getPowerDataList('2')" placeholder="请选择" size="small" style="margin:0 16px;"></el-date-picker>
            <el-button plain icon="el-icon-arrow-right" size="small" @click="addMonth(1)"></el-button>
          </div>
          <div id="energyTrend_analysis_bar2" style="height:300px;" class="mt-2"></div>
        </div>
        
        <div class="mt-6">
          <div>
            <el-button plain icon="el-icon-arrow-left" size="small" @click="addYear(-1)"></el-button>
            <el-date-picker v-model="dataForm.yearDate" type="year" value-format="yyyy" @change="getPowerDataList('3')" placeholder="请选择" size="small" style="margin:0 16px;"></el-date-picker>
            <el-button plain icon="el-icon-arrow-right" size="small" @click="addYear(1)"></el-button>
          </div>
          <div id="energyTrend_analysis_bar3" style="height:300px;" class="mt-2"></div>
        </div>
      </el-col>
    </el-row>
  </d2-container>
</template>

<script>
  import { mapGetters } from 'vuex'
  import areaTree from './compont/area_tree_onceclick'
  import * as echarts from 'echarts'
  import dayjs from 'dayjs'
  import * as Util from "@/utils";
  export default {
    name: 'energyTrend',
    data() {
      return {
        buildList:'',
        dataForm:{
          energyType: '',
          dayDate: Util.dateFormat('YYYYmmdd', new Date()),
          monthDate: Util.dateFormat('YYYYmm', new Date()),
          yearDate: Util.dateFormat('YYYY', new Date())
        },
        date1: dayjs(),
        date2: dayjs(),
        date3: dayjs(),
        meterTypeList:[],
        currentUnit:""
      }
    },
    computed: {
      ...mapGetters('d2admin/theme', ['activeSetting'])
    },
    components: {
      areaTree
    },
    created() {
      this.$nextTick(()=>{
        this.queryStatic("METER_TYPE",null,data=>{
          if (data && data.code === 0) {
            this.meterTypeList = data.page
            this.dataForm.energyType = data.page[0].paramKey;
            this.currentUnit = data.page[0].paramExt;
          } else {
            this.meterTypeList = []
          }
           this.getPowerDataListAll();
        });
      })
    },
    watch: {
      'activeSetting.name': {
        handler() {
          this.drawBar1()
          this.drawBar2()
          this.drawBar3()
        },
        immediate: true,
      },
      'dataForm.energyType':function(newV,oldV){
        this.currentUnit = this.meterTypeList.find(item => item.paramKey == newV).paramExt;
      },
    },
    methods: {
      addDate(num){
        let time =  new Date(this.dataForm.dayDate.slice(0,4),this.dataForm.dayDate.slice(4,6)-1,this.dataForm.dayDate.slice(6,8))
        time.setDate(time.getDate() + num)
        this.dataForm.dayDate = Util.dateFormat('YYYYmmdd', time)
        this.getPowerDataList('1')
      },
      addMonth(num){
        console.log(this.dataForm.monthDate.slice(4,6))
        let time =  new Date(this.dataForm.monthDate.slice(0,4),this.dataForm.monthDate.slice(4,6)-1,1)
        console.log(time.getMonth())
        if(num>0){
          time.setMonth(time.getMonth() + 1)
        }else {
          time.setMonth(time.getMonth() - 1)
        }
        this.dataForm.monthDate = Util.dateFormat('YYYYmm', time)
        this.getPowerDataList('2')
      },
      addYear(num){
        let time =  new Date(this.dataForm.yearDate.slice(0,4),2,0)
        time.setFullYear(time.getFullYear() + num)
        this.dataForm.yearDate = Util.dateFormat('YYYY', time)
        this.getPowerDataList('3')
      },

      objArraySort(objArr, key)
      {
        let result = objArr.slice(0);
        return result.sort((a, b) => parseInt(a[key]) - parseInt(b[key]));
      },
      queryStatic(type,paramValue,callback) {
        let params = {
          'code': type ,
          "customerId":this.$util.cookies.get('customer_id')
        }
        if(paramValue){
          Object.assign(params,{paramValue,paramValue});
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then((data) => {
          if(callback){
            callback(data);
          }
        });
      },
      treeNodeChange(data){
        this.buildList = data
        this.getPowerDataListAll()
      },
      getPowerDataListAll(showType){
        this.getPowerDataList("1")
        this.getPowerDataList("2")
        this.getPowerDataList("3")
      },
      getPowerDataList(showType){
        if(this.dataForm.energyType ==''|| this.buildList == ''){
          return
        }

        if(showType == "1") {
          const chart = echarts.init(document.querySelector('#energyTrend_analysis_bar1'))
          chart.clear()
          this.getPowerList(showType,this.dataForm.dayDate);
        }else if(showType == "2") {
          const chart = echarts.init(document.querySelector('#energyTrend_analysis_bar2'))
          chart.clear()
          this.getPowerList(showType,this.dataForm.monthDate);
        }else if(showType == "3") {
          const chart = echarts.init(document.querySelector('#energyTrend_analysis_bar3'))
          chart.clear()
          this.getPowerList(showType,this.dataForm.yearDate);
        }

      },
      getPowerList(dateType,date) {
        this.$api.okhttp({
          url:this.$http.adornUrl('/eas/energyTrend/list'),
          method: "post",
          data: this.$http.adornParams(
            {
              buildingIds: [this.buildList],
              date: date,
              dateType: dateType,
              meterType: this.dataForm.energyType,
              customerId: this.$util.cookies.get("customer_id"),
              projectId:this.$util.cookies.get("cuuren_projectId")
            }
          )
        }).then((data) => {
          if (data && data.code === 0) {
            let valueArry = []
            let valueLastArry = []
            if(data.data.length>0) {
              let val = data.data[0].val;
              Object.keys(val).forEach((key) => {
                valueArry.push({"id": key, "value": val[key]})
              })
              valueArry = this.objArraySort(valueArry, "id")
            }
            if(data.last.length>0) {
              let val = data.last[0].val;
              Object.keys(val).forEach((key) => {
                valueLastArry.push({"id": key, "value": val[key]})
              })
              valueLastArry = this.objArraySort(valueLastArry, "id")
            }

            let xMax = 0;
            let ydataLast = []
            if(dateType == '1'){
              xMax = new Date().getHours();
              valueArry = valueArry.slice(0,xMax+1)
              let xdata = valueArry.map(i=>i.id)
              let ydata = valueArry.map(i=>i.value)
              ydataLast = valueLastArry.map(i=>i.value)
              this.drawBar1(xdata,ydata,ydataLast)
            }else if(dateType == '2'){
              xMax = new Date().getDate();
              valueArry = valueArry.slice(0,31)
              let xdata = valueArry.map(i=>i.id)
              let ydata = valueArry.map(i=>i.value)
              ydataLast = valueLastArry.map(i=>i.value)
              this.drawBar2(xdata,ydata,ydataLast)
            } else if(dateType == '3'){
              xMax = new Date().getMonth()+1;
              valueArry = valueArry.slice(0,xMax)
              let xdata = valueArry.map(i=>i.id)
              let ydata = valueArry.map(i=>i.value)
              ydataLast = valueLastArry.map(i=>i.value)
              this.drawBar3(xdata,ydata,ydataLast)
            }

          }
        })

      },


      drawBar1(xdata,ydata,ydataLast) {
        this.$nextTick(() => {
          const chart = echarts.init(document.querySelector('#energyTrend_analysis_bar1'))
          chart.setOption({
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            grid: {
              left: '5%',
              right: '5%',
              top: '18%',
              bottom: '10%'
            },
            xAxis: {
              type: 'category',
              data: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23].map(i => (i < 9 ? '0' + i : i) + ':00'),
              axisLine: {
                lineStyle: {
                  color: this.activeSetting.name === 'd2' ? '#333' : '#999'
                },
              },
            },
            yAxis: {
              type: 'value',
              axisLine: {
                lineStyle: {
                  color: this.activeSetting.name === 'd2' ? '#333' : '#999'
                },
              },
              splitLine: {
                show: true,
                lineStyle: {
                  color: ['#999']
                },
              },
            },
            legend: {
              right: 20,
              textStyle: {
                color: this.activeSetting.name === 'd2' ? '#333' : '#ccc'
              },
            },
            series: [
              {
                data: ydata,
                type: 'bar',
                name: '当日',
                markPoint: {
                  data: [
                    { type: 'max', name: 'Max' },
                    { type: 'min', name: 'Min' }
                  ]
                }
              },
              {
                data: ydataLast,
                type: 'bar',
                name: '昨日',
                markPoint: {
                  data: [
                    { type: 'max', name: 'Max' },
                    { type: 'min', name: 'Min' }
                  ]
                }
              },
            ]
          })
        })
      },
      drawBar2(xdata,ydata,ydataLast) {
        this.$nextTick(() => {
          const chart = echarts.init(document.querySelector('#energyTrend_analysis_bar2'))
          chart.setOption({
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            grid: {
              left: '5%',
              right: '5%',
              top: '18%',
              bottom: '10%'
            },
            xAxis: {
              type: 'category',
              data: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,17,28,29,30,31].map(i => (i < 9 ? '0' + i : i) + ''),
              axisLine: {
                lineStyle: {
                  color: this.activeSetting.name === 'd2' ? '#333' : '#999'
                },
              },
            },
            yAxis: {
              type: 'value',
              axisLine: {
                lineStyle: {
                  color: this.activeSetting.name === 'd2' ? '#333' : '#999'
                },
              },
              splitLine: {
                show: true,
                lineStyle: {
                  color: ['#999']
                },
              },
            },
            legend: {
              right: 20,
              textStyle: {
                color: this.activeSetting.name === 'd2' ? '#333' : '#ccc'
              },
            },
            series: [
              {
                data: ydata,
                type: 'bar',
                name: '当月',
                markPoint: {
                  data: [
                    { type: 'max', name: 'Max' },
                    { type: 'min', name: 'Min' }
                  ]
                }
              },
              {
                data:ydataLast,
                type: 'bar',
                name: '上月',
                markPoint: {
                  data: [
                    { type: 'max', name: 'Max' },
                    { type: 'min', name: 'Min' }
                  ]
                }
              },
            ]
          })
        })
      },
      drawBar3(xdata,ydata,ydataLast) {
        this.$nextTick(() => {
          const chart = echarts.init(document.querySelector('#energyTrend_analysis_bar3'))
          chart.setOption({
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            grid: {
              left: '5%',
              right: '5%',
              top: '18%',
              bottom: '10%'
            },
            xAxis: {
              type: 'category',
              data: [1,2,3,4,5,6,7,8,9,10,11,12].map(i => (i < 9 ? '0' + i : i) + ''),
              axisLine: {
                lineStyle: {
                  color: this.activeSetting.name === 'd2' ? '#333' : '#999'
                },
              },
            },
            yAxis: {
              type: 'value',
              axisLine: {
                lineStyle: {
                  color: this.activeSetting.name === 'd2' ? '#333' : '#999'
                },
              },
              splitLine: {
                show: true,
                lineStyle: {
                  color: ['#999']
                },
              },
            },
            legend: {
              right: 20,
              textStyle: {
                color: this.activeSetting.name === 'd2' ? '#333' : '#ccc'
              },
            },
            series: [
              {
                data: ydata,
                type: 'bar',
                name: '当年',
                markPoint: {
                  data: [
                    { type: 'max', name: 'Max' },
                    { type: 'min', name: 'Min' }
                  ]
                }
              },
              {
                data: ydataLast,
                type: 'bar',
                name: '去年',
                markPoint: {
                  data: [
                    { type: 'max', name: 'Max' },
                    { type: 'min', name: 'Min' }
                  ]
                }
              },
            ]
          })
        })
      },
    },
  }
</script>

<style>
</style>
